package com.sfh.cp.user;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sfh.cp.R;
import com.sfh.cp.base.AbstractBaseActivity;
import com.sfh.cp.user.pst.IPstUserInfo;
import com.sfh.cp.widget.WidgetBaseToolbar;
import com.sfh.lib.mvp.IPresenter;
import com.sfh.lib.mvp.service.LoaderService;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import crm.sfh.server.entity.City;
import crm.sfh.server.entity.ECity;
import crm.sfh.server.entity.EDegreeType;
import crm.sfh.server.entity.EUser;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class UserActivity extends AbstractBaseActivity implements IPstUserInfo.IVUserInfo {
    @BindView(R.id.ivHead)
    CircleImageView ivHead;

    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.tvZY)
    TextView tvZY;
    @BindView(R.id.tvCity)
    TextView tvCity;
    @BindView(R.id.rgSex)
    RadioGroup rgSex;
    @BindView(R.id.toolbar)
    WidgetBaseToolbar toolbar;

    public static void startUI(Context context) {
        Intent intent = new Intent(context, UserActivity.class);
        context.startActivity(intent);
    }

    IPstUserInfo pstUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_activity);
        ButterKnife.bind(this);
        toolbar.setTitle("个人资料");
        toolbar.setBackFinish();
        pstUserInfo.getUser();
    }

    @Override
    public IPresenter getPresenter() {
        if (pstUserInfo == null) {
            pstUserInfo = LoaderService.getService(IPstUserInfo.class);
        }
        return pstUserInfo;
    }

    @OnClick({R.id.ivHead, R.id.lyHead, R.id.tvZY, R.id.tvCity})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivHead:
            case R.id.lyHead:
                // 头像
                this.hasPermissions();
                break;
            case R.id.tvZY:

                pstUserInfo.listDegreeType();
                break;
            case R.id.tvCity:
                pstUserInfo.listCity();
                break;
        }
    }

    @Override
    public void onUserInfo(EUser user) {
        tvCity.setText(user.getAddress());
        tvZY.setText(user.getDegree());
        rgSex.check(TextUtils.equals("1", user.getSex()) ? R.id.cbM : R.id.rbW);
        etName.setText(user.getName());
        if (TextUtils.isEmpty(user.getHead())) {
            this.ivHead.setImageResource(R.mipmap.userimg_default);
        } else {
            Picasso.with(getApplicationContext()).load(user.getHead()).into(this.ivHead);
        }
        rgSex.setOnCheckedChangeListener(null);
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                ReqUserInfo req = new ReqUserInfo();
                if (checkedId == R.id.cbM) {
                    req.setSex("1");
                } else {
                    req.setSex("0");
                }
                pstUserInfo.updateUser(req);
            }
        });
        addTextChangedListener(user);
    }


    @Override
    public void onCity(final List<ECity> list) {

        final List<List<City>> item2 = new ArrayList<>(list.size());
        for (ECity city : list) {
            item2.add(city.getCitys());
        }
        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvCity.setText(list.get(options1).getCitys().get(option2).getCitysName());
                ReqUserInfo req = new ReqUserInfo();
                req.setAddress(list.get(options1).getCitys().get(option2).getCitysName());
                pstUserInfo.updateUser(req);
            }
        }).build();
        pvOptions.setPicker(list, item2);
        pvOptions.show();
    }

    @Override
    public void onDegreeType(final List<EDegreeType> list) {
        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvZY.setText(list.get(options1).getName());
                ReqUserInfo req = new ReqUserInfo();
                req.setDegreeType(list.get(options1).getType());
                pstUserInfo.updateUser(req);
            }
        }).build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    @Override
    public String[] getPermissions() {
        return new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    }

    @Override
    public void onPermissionsSuccess() {
        MultiImageSelector.create().showCamera(true)
                .count(1).multi().start(this, 10101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10101 && resultCode == RESULT_OK) {
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if (path == null || path.isEmpty()) {
                return;
            }
            Picasso.with(getApplicationContext()).load(new File(path.get(0))).into(this.ivHead);
            ReqUserInfo req = new ReqUserInfo();
            req.setHead(path.get(0));
            pstUserInfo.updateUser(req);
        }
    }

    private void addTextChangedListener(EUser user) {

        etName.removeTextChangedListener(textWatcher);
        etName.setText(user.getName());
        Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final ObservableEmitter<String> emitter) throws Exception {
                etName.addTextChangedListener(getTextWatcher(emitter));
            }
        }).debounce(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread()).filter(new Predicate<String>() {
                    @Override
                    public boolean test(String content) throws Exception {
                        return content.trim().length() > 0;
                    }
                }).map(new Function<String, Boolean>() {
                    @Override
                    public Boolean apply(String content) throws Exception {
                        ReqUserInfo req = new ReqUserInfo();
                        req.setName(content);
                        pstUserInfo.updateUser(req);
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe();
        pstUserInfo.putDisposable(0x120, disposable);
    }

    TextWatcher textWatcher;

    private TextWatcher getTextWatcher(final ObservableEmitter<String> emitter) {

        if (textWatcher == null) {
            textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    emitter.onNext(s.toString());
                }
            };
        }

        return textWatcher;
    }

}
